//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	NamedEventHandlerInfoMap.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;

namespace Smart.Common
{
	public class NamedEventHandlerInfoMap : Dictionary<string, NamedEventHandlerInfoArray>
	{
		public NamedEventHandlerInfoMap()
			: base(StringComparer.OrdinalIgnoreCase)
		{
		}

		public string GetKey(string webName, string eventName)
		{
			return webName + "#" + eventName;
		}

		public void Register(string webName, string eventName, Delegate handler, int priority)
		{
			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array == null)
				this[key] = array = new NamedEventHandlerInfoArray();

			array.Register(handler, priority);
		}

		public void Unregister(string webName, string eventName, Delegate handler)
		{
			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array != null)
			{
				array.Unregister(handler);

				if (array.Count <= 0)
					Remove(key);
			}
		}

		public void Unregister(string webName, string eventName)
		{
			var key = GetKey(webName, eventName);

			Remove(key);
		}

		public bool FireEvent<TArg1>(string webName, string eventName, TArg1 arg1)
		{
			var res = true;

			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array != null)
				res = array.FireEvent(eventName, arg1);

			return res;
		}

		public bool FireEvent<TArg1, TArg2>(string webName, string eventName, TArg1 arg1, TArg2 arg2)
		{
			var res = true;

			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array != null)
				res = array.FireEvent(eventName, arg1, arg2);

			return res;
		}

		public bool FireEvent<TArg1, TArg2, TArg3>(string webName, string eventName, TArg1 arg1, TArg2 arg2, TArg3 arg3)
		{
			var res = true;

			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array != null)
				res = array.FireEvent(eventName, arg1, arg2, arg3);

			return res;
		}

		public bool FireEvent<TArg1, TArg2, TArg3, TArg4>(string webName, string eventName, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4)
		{
			var res = true;

			var key = GetKey(webName, eventName);

			NamedEventHandlerInfoArray array;

			TryGetValue(key, out array);

			if (array != null)
				res = array.FireEvent(eventName, arg1, arg2, arg3, arg4);

			return res;
		}
	}
}